package sdu.icat.pj.service;

import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import sdu.icat.pj.repository.SysArticleRepository;
import sdu.icat.pj.support.SimpleSpecification;
import sdu.icat.sys.smodel.SysArticle;

@Service("sys_article_service")
public class SysArticleService {

    @Autowired private SysArticleRepository sysArticleRepository;
    
    @Transactional
    public Page<SysArticle> listAll(int page,int size) {
	Sort sort = new Sort(Direction.DESC,"id");
	PageRequest pageable = new PageRequest(page,size,sort);
	return sysArticleRepository.findAll(pageable);
    }
    
    @Transactional
    public Page<SysArticle> listParams(Map<String,Object> params) {
	Sort sort = new Sort(Direction.DESC,"id");
	Integer page = (Integer) params.getOrDefault("page", 0);
	Integer size = (Integer) params.getOrDefault("size", 20);
	PageRequest pageable = new PageRequest(page,size,sort);
	return sysArticleRepository.findAll(new SimpleSpecification<SysArticle>(params, SysArticle.class), pageable);
    }
    
    @Transactional
    public SysArticle save(SysArticle article) {
	sysArticleRepository.saveAndFlush(article);
	return article;
    }
    
    @Transactional
    public void delete(SysArticle article) {
	sysArticleRepository.delete(article);
    }
    
    @Transactional
    public boolean delete(long id) {
	sysArticleRepository.delete(id);
	return true;
    }
    
    @Transactional
    public boolean delete(long[] ids) {
	for(int i=0;i<ids.length;i++) {
	    try {
		sysArticleRepository.delete(ids[i]);
	    } catch (Exception e) {
		return false;
	    }
	}
	return true;
    }
    
    @Transactional
    public SysArticle query(long id) {
	return sysArticleRepository.findOne(id);
    }
}
